<template>
  <div class="report-manage">
    <div class="filter-bar-wrapper">
      <FilterBar
        :status="status"
        showStatus
        :isReport="true"
        @update:status="status = $event"
      />
    </div>

    <LoadingWrapper :loading="loading">
      <div>
        <el-tabs v-model="activeTab">
          <el-tab-pane label="全部" name="all">
            <el-table 
              v-if="filteredReports.length > 0"
              :data="paginatedReports"
              style="width: 100%" 
              :cell-style="{ padding: '12px 0' }"
            >
              <el-table-column 
                prop="index" 
                label="序号" 
                width="80"
                align="center"
              />

              <el-table-column
                prop="title"
                label="被举报内容"
                min-width="180"
                align="center"
                show-overflow-tooltip
              >
                <template #default="{ row }">
                  <el-button 
                    type="primary" 
                    link
                    @click="viewBook(row.post_id)"
                  >
                    {{ row.title }}
                  </el-button>
                </template>
              </el-table-column>

              <el-table-column
                prop="report_user_name"
                label="举报人"
                min-width="120"
                align="center"
                show-overflow-tooltip
              />

              <el-table-column
                prop="reported_user_name"
                label="被举报人"
                min-width="120"
                align="center"
                show-overflow-tooltip
              />

              <el-table-column
                prop="report_type"
                label="举报类型"
                min-width="120"
                align="center"
              >
                <template #default="{ row }">
                  <el-tag
                    :type="getReportTypeTag(row.report_type)"
                    size="small"
                  >
                    {{ getReportTypeLabel(row.report_type) }}
                  </el-tag>
                </template>
              </el-table-column>

              <el-table-column
                prop="report_reason"
                label="举报原因"
                min-width="200"
                align="center"
                show-overflow-tooltip
              />

              <el-table-column
                prop="created_at"
                label="举报时间"
                width="180"
                align="center"
              >
                <template #default="{ row }">
                  {{ formatDateTime(row.created_at) }}
                </template>
              </el-table-column>

              <el-table-column
                prop="status"
                label="状态"
                width="100"
                align="center"
              >
                <template #default="{ row }">
                  <el-tag
                    :type="getStatusType(row.status)"
                    size="small"
                  >
                    {{ getStatusLabel(row.status) }}
                  </el-tag>
                </template>
              </el-table-column>

              <el-table-column 
                label="操作" 
                width="200"
                fixed="right"
                align="center"
              >
                <template #default="{ row }">
                  <div class="operation-cell">
                    <el-button
                      v-if="row.status === 'processed'"
                      type="primary"
                      link
                      @click="viewHandleRecord(row)"
                    >
                      <el-icon><View /></el-icon>
                    </el-button>

                    <el-tooltip 
                      v-if="row.status === 'pending'"
                      content="处理" 
                      placement="top"
                    >
                      <el-button
                        type="success"
                        link
                        @click="handleReportAction(row)"
                      >
                        <el-icon><CircleCheckFilled /></el-icon>
                      </el-button>
                    </el-tooltip>

                    <el-tooltip 
                      v-if="row.status === 'pending'"
                      content="驳回" 
                      placement="top"
                    >
                      <el-button
                        type="danger"
                        link
                        @click="handleRejectReport(row)"
                      >
                        <el-icon><CircleCloseFilled /></el-icon>
                      </el-button>
                    </el-tooltip>

                    <el-tooltip 
                      content="删除" 
                      placement="top"
                    >
                      <el-button
                        type="danger"
                        link
                        @click="handleDelete(row)"
                      >
                        <el-icon><Delete /></el-icon>
                      </el-button>
                    </el-tooltip>
                  </div>
                </template>
              </el-table-column>
            </el-table>
            <el-empty v-else description="暂无数据" />
          </el-tab-pane>
        </el-tabs>
      </div>
    </LoadingWrapper>

    <div class="pagination-wrapper">
      <PaginationBar
        v-if="filteredReports.length > 0"
        v-model:currentPage="currentPage"
        v-model:pageSize="pageSize"
        :total="filteredReports.length"
        :pageSizes="[10, 15, 20, 25]"
        @pagination-change="handlePaginationChange"
      />
    </div>

    <el-dialog
      v-model="dialogVisible"
      title="处理举报"
      width="500px"
      :close-on-click-modal="false"
    >
      <el-form ref="formRef" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="处理结果" prop="result">
          <el-radio-group v-model="form.result">
            <el-radio label="block">屏蔽内容</el-radio>
            <el-radio label="warn">警告用户</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="处理说明">
          <el-input
            v-model="form.comment"
            type="textarea"
            :rows="4"
            :maxlength="500"
            placeholder="请输入处理说明..."
            resize="none"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitHandle">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <el-dialog
      v-model="viewDialogVisible"
      title="处理记录"
      width="400px"
    >
      <div class="handle-record">
        <div class="record-item">
          <span class="label">处理结果：</span>
          <span>{{ 
            viewingReport?.handle_result === 'rejected' ? '驳回举报' :
            viewingReport?.handle_result === 'block' ? '屏蔽内容' :
            viewingReport?.handle_result === 'warn' ? '警告用户' : ''
          }}</span>
        </div>
        <div class="record-item" v-if="viewingReport?.handle_comment">
          <span class="label">处理说明：</span>
          <span>{{ viewingReport?.handle_comment }}</span>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, computed, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  Delete,        
  DocumentChecked, 
  CircleCloseFilled,
  CircleCheckFilled,
  View
} from '@element-plus/icons-vue'
import { getReportList, handleReport, rejectReport, deleteReport } from '@/api/report'
import { sendNotification } from '@/api/notification'
import { unpublishBook } from '@/api/book'
import { formatDateTime } from '@/utils/format'
import FilterBar from '@/components/filter/FilterBar.vue'
import PaginationBar from '@/components/pagination/PaginationBar.vue'
import LoadingWrapper from '@/components/loading/LoadingWrapper.vue'

const activeTab = ref('all')
const dialogVisible = ref(false)
const currentReport = ref(null)
const reports = ref([])
const viewDialogVisible = ref(false)
const viewingReport = ref(null)
const status = ref('1') // '1'表示全部，'2'表示已处理，'0'表示未处理

// 表单相关
const formRef = ref(null)
const form = ref({
  result: '',
  comment: ''
})

const rules = {
  result: [{ required: true, message: '请选择处理结果', trigger: 'change' }]
}

// 分页相关
const currentPage = ref(1)
const pageSize = ref(10)

// 添加 loading 状态
const loading = ref(true)

// 获取举报列表
const getReports = async () => {
  try {
    loading.value = true
    const response = await getReportList()
    if (response.code === 200) {
      reports.value = response.data.map((report, index) => ({
        ...report,
        index: index + 1,
        title: report.post_title
      }))
    } else {
      ElMessage.error(response.message || '获取举报列表失败')
    }
  } catch (error) {
    console.error('加载举报列表失败:', error)
    ElMessage.error('加载失败，请稍后重试')
  } finally {
    loading.value = false
  }
}

// 过滤举报列表
const filteredReports = computed(() => {
  return reports.value.filter(report => {
    // 状态筛选逻辑
    return status.value === '1' || 
      (status.value === '2' && report.status === 'processed') || 
      (status.value === '0' && report.status === 'pending')
  })
})

// 分页后的举报列表
const paginatedReports = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  return filteredReports.value.slice(start, end)
})

// 处理分页变化
const handlePaginationChange = ({ type, value }) => {
  if (type === 'page') {
    currentPage.value = value
  } else if (type === 'size') {
    pageSize.value = value
    currentPage.value = 1
  }
}

// 监听筛选条件变化，重置页码
watch(status, () => {
  currentPage.value = 1
})

// 处理举报
const handleReportAction = async (report) => {
  if (report.status === 'processed') {
    ElMessage.warning('该举报已处理')
    return
  }
  currentReport.value = report
  dialogVisible.value = true
  form.value = { 
    result: '', 
    comment: '' 
  }
}

// 提交处理
const submitHandle = async () => {
  if (!formRef.value) return

  try {
    await formRef.value.validate()
    const res = await handleReport(currentReport.value.id, {
      handleResult: form.value.result,
      handleComment: form.value.comment
    })
    
    if (res.code === 200) {
      ElMessage.success('处理成功')
      currentReport.value.status = 'processed'
      currentReport.value.handle_result = form.value.result
      currentReport.value.handle_comment = form.value.comment
      
      // 发送通知给举报人
      await sendNotification({
        userId: currentReport.value.report_user_id,
        type: 'report_accepted',
        title: '举报处理通知',
        content: `您对"${currentReport.value.post_title}"的举报已被处理，处理结果：${
          form.value.result === 'block' ? '屏蔽内容，感谢您的举报' : '警告用户，感谢您的举报'
        }`,
        relatedId: currentReport.value.post_id
      })

      // 发送通知给被举报人
      await sendNotification({
        userId: currentReport.value.reported_user_id,
        type: 'report_warning',
        title: '内容违规通知',
        content: `您的内容"${currentReport.value.post_title}"被举报且已确认违规，请注意内容质量`,
        relatedId: currentReport.value.post_id
      })

      // 如果选择屏蔽内容，则下架书籍
      if (form.value.result === 'block') {
        await unpublishBook(currentReport.value.post_id)
      }
      
      dialogVisible.value = false
    }
  } catch (error) {
    if (error.name === 'ValidationError') return
    console.error('提交处理结果失败:', error)
    ElMessage.error(error.message || '提交失败，请稍后重试')
  }
}

// 驳回举报
const handleRejectReport = async (row) => {
  try {
    const res = await handleReport(row.id, {
      handleResult: 'rejected'
    })
    if (res.code === 200) {
      ElMessage.success('驳回成功')
      row.status = 'processed'
      row.handle_result = 'rejected'
      
      // 发送通知给举报人
      await sendNotification({
        userId: row.report_user_id,
        type: 'report_rejected',
        title: '举报驳回通知',
        content: `您对"${row.post_title}"的举报已被驳回`,
        relatedId: row.post_id
      })
    }
  } catch (error) {
    console.error('驳回举报失败:', error)
    ElMessage.error('驳回失败')
  }
}

// 删除举报
const handleDelete = async (row) => {
  try {
    await deleteReport(row.id)
    ElMessage.success('已删除')
    getReports()
  } catch (error) {
    console.error('删除失败:', error)
    ElMessage.error(error.message || '删除失败，请稍后重试')
  }
}

// 跳转书籍详情
const viewBook = (bookId) => {
  window.open(`/books/${bookId}`, '_blank')
}

// 获取举报类型标签
const getReportTypeTag = (type) => {
  const tags = {
    inappropriate: 'warning',
    spam: 'info',
    illegal: 'danger',
    other: ''
  }
  return tags[type] || ''
}

// 获取举报类型标签文本
const getReportTypeLabel = (type) => {
  const labels = {
    inappropriate: '内容不当',
    spam: '垃圾信息',
    illegal: '违法信息',
    other: '其他'
  }
  return labels[type] || type
}

// 获取状态类型
const getStatusType = (status) => {
  const types = {
    pending: '',
    processed: 'success',
    rejected: 'info'
  }
  return types[status] || ''
}

// 获取状态标签
const getStatusLabel = (status) => {
  const labels = {
    pending: '待处理',
    processed: '已处理',
    rejected: '已驳回'
  }
  return labels[status] || status
}

// 查看处理记录
const viewHandleRecord = (row) => {
  viewingReport.value = row
  viewDialogVisible.value = true
}

onMounted(() => {
  getReports()
})
</script>

<style scoped>
.report-manage {
  padding: 20px;
}

.filter-bar-wrapper {
  display: flex;
  justify-content: flex-end;
}

.operation-cell {
  display: flex;
  justify-content: center;
  gap: 6px;
}

:deep(.el-tag) {
  margin: 0 4px;
}

.el-icon {
  font-size: 18px;
}

:deep(.el-button) {
  padding: 0;
}

.handle-record {
  padding: 20px;
}
.record-item {
  margin-bottom: 15px;
}
.record-item .label {
  font-weight: bold;
  margin-right: 10px;
}

.pagination-wrapper {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}

.pagination-wrapper :deep(.el-pagination) {
  display: flex;
  justify-content: flex-end;
}
</style> 